const db = wx.cloud.database()
import WxValidate from '../../utils/WxValidate'
var req = require("../../utils/action.js");
var utils = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    imageList: [],
    verifyText: '',
    images:[],
    submitImagePath:[],
    myAvatar:'',
    avatarList:null,
    avatarUrl:'',
    agree_privacy:false,
    showPopup:false,
    agree_user_privacy:false,
    agree_yuanze:false,
    show:false,
    chooseType:1,
    verifyType:1,
    mailText:"发送验证码",
    randomCode:"",
    ifVerify:"1",
    mailBtnStatus:false,
    timer:null,
    countSeconds:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
    this.initValidate()
    let userInfo = getApp().globalData.userInfo
    console.log("userInfouserInfo",userInfo)
    if(userInfo && userInfo.myAvatarUrl){ 
      this.setData({
        avatarList:[
          {type:"image",url:userInfo.myAvatarUrl}
        ],
        agreePrivacy:userInfo.agreePrivacy == '1',
        agreeYuanze:true,
        agreeUserPrivacy:true
      })
    }
    console.log("agree_privacy",this.data.agree_privacy)
    console.log(userInfo)
    this.setData({
      ifVerify:userInfo.if_verify ? userInfo.if_verify : "0",
      verifyType:userInfo.email?2:1,
      userInfo:userInfo,
      verifyText: (userInfo && userInfo.if_valid == 'Y')?'已审核通过':(userInfo && userInfo.name?'审核中':'')
    })
    
  },
  onReady: function () {},
  onShow: function () {
    if(this.data.show){
      return
    }
    let userInfo = getApp().globalData.userInfo
    if(!userInfo) return;
    if(userInfo && userInfo.my_avatar_url){ 
      this.setData({avatarList:[{type:"image",url:userInfo.my_avatar_url}],agree_privacy:userInfo.agree_privacy == '1'})
    }
    console.log(userInfo)
    this.setData({
      show: true,
      userInfo:userInfo,
      verifyText: (userInfo.if_valid == 'Y')?'已审核通过':(userInfo.name?'审核中':'')
    })
    
  },
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  onShareAppMessage: function () {},
  afterAvatarRead(event){
    let that = this,files = event.detail.file,avatarList=[]
    console.log("avatarList files:"+JSON.stringify(files))
    avatarList[0] = files[0]
    console.log(avatarList)
    that.setData({avatarList: avatarList})
    console.log(that.data.avatarList)
  },
  changeYuanze(){
    this.setData({agree_yuanze:!this.data.agree_yuanze})
    console.log(this.data.agree_yuanze)
  },
  verifyTypeChange(e){
    console.log(e)
    this.setData({verifyType:e.detail.value})
  },
  readYuanze(){
    console.log("readPrivacyreadPrivacyreadPrivacyreadPrivacy")
    wx.navigateTo({
      url: './yuanze',
    })
  },
  changeUserPrivacy(){
    this.setData({agree_user_privacy:!this.data.agree_user_privacy})
    console.log(this.data.agree_user_privacy)
  },
  readUserPrivacy(){
    console.log("readPrivacyreadPrivacyreadPrivacyreadPrivacy")
    wx.navigateTo({
      url: './userPrivacy',
    })
  },
  changePrivacy(){
    this.setData({agree_privacy:!this.data.agree_privacy})
    console.log(this.data.agree_privacy)
  },
  readPrivacy(){
    this.setData({showPopup:!this.data.showPopup})
    console.log("readPrivacyreadPrivacyreadPrivacyreadPrivacy")
    wx.navigateTo({
      url: './privacy',
    })
  },
  afterRead(event) {
    let that = this
    console.log(event)
    let files = event.detail.file
    for(var i=0;i<files.length;i++){
      this.data.images = this.data.images.concat(files[i].url)
    }
    console.log(that.data.imageList.concat(event.detail.file))
    that.setData({
      imageList: that.data.imageList.concat(event.detail.file)
    })
    //console.log(this.data.images)
    //utils.savePiture(_url,this.data.images,'zjz',function(imagePath){})
   
  },
  onAvatarDelete(event) {
    console.log(event.detail.index)
    this.data.avatarList.splice(event.detail.index, 1)
    this.setData({
      avatarList: this.data.avatarList
    })
  },
  onDelete(event) {
    console.log(event.detail.index)
    this.data.imageList.splice(event.detail.index, 1)
    this.setData({
      imageList: this.data.imageList
    })
  },
  onPreviewImage(event) {
    wx.previewImage({
      urls: this.data.userInfo.img,
      current: event.target.dataset.imgsrc
    })
  },
  syncUpload(method,_url,imagePath){   //定义一个方法b

    return new Promise((reslove, reject) => {
      utils.upload(_url,imagePath,'zjz',1,function(res){
        if(res == 'fail'){
          wx.showToast({
            title: '发布失败，请重试',
            icon: 'error'
          })
        }else{
          that.data.submitImagePath = that.data.submitImagePath.concat(res)
        }
      })
    });
  },
  formSubmit(e) {
    console.log("this.data.verifyType===》"+this.data.verifyType)
    let params = e.detail.value, that = this,_url = req.actions.ym+ "file/uploadPicture"
    console.log(params)
    if(!this.data.agree_yuanze){
      wx.showToast({
        title: '必须先阅读并同意用户原则才能提交哦~',
        icon: 'none'
      })
      return false
    }
    if(!this.data.agree_user_privacy){
      wx.showToast({
        title: '必须先阅读并同意用户协议才能提交哦~',
        icon: 'none'
      })
      return false
    }
    if(!this.data.agree_privacy){
      wx.showToast({
        title: '必须先阅读并同意隐私协议才能提交哦~',
        icon: 'none'
      })
      return false
    }
    
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      wx.showToast({
        title: error.msg,
        icon: 'none'
      })
      return false
    }
    if(!this.data.userInfo.name){
      if(this.data.verifyType == '1' && this.data.imageList.length==0) {
        wx.showToast({
          title: '请上传有效的证件照片（至少一张）',
          icon: 'none'
        })
        return false
      }else if(this.data.verifyType == '2' && !this.data.email){
        wx.showToast({
          title: '请填写邮箱~',
          icon: 'none'
        })
        return false
      }
      if(this.data.avatarList.length==0 && !this.data.userInfo.my_avatar_url) {
        wx.showToast({
          title: '请上传一张个人头像！',
          icon: 'none'
        })
        return false
      }
      if(this.data.verifyType == '2' && (!this.data.randomCode || this.data.randomCode.trim().length == 0)){
        wx.showToast({
          title: '请填写邮箱验证码！',
          icon: 'none'
        })
        return false
      }
      wx.showLoading({
        title: '发布中',
        mask: true,
      })
      let promiseArr = []
      // 图片上传
      let ava = new Promise((resolve, reject) => {
        utils.upload(_url,this.data.avatarList[0].url,'zjz',1,function(res){
          if(res == 'fail'){
            wx.showToast({
              title: '发布失败，请重试',
              icon: 'error'
            })
            reject()
          }else{
            that.data.avatarUrl = res
            resolve()
          }
        })
      })
      promiseArr.push(ava)
      const imageList = this.data.imageList
      if(imageList.length > 0){
        for (let i = 0, len = imageList.length; i < len; i++) {
          let p = new Promise((resolve, reject) => {
            let item = imageList[i].url
            utils.upload(_url,item,'zjz',1,function(res){
              if(res == 'fail'){
                wx.showToast({
                  title: '发布失败，请重试',
                  icon: 'error'
                })
                reject()
              }else{
                that.data.submitImagePath = that.data.submitImagePath.concat(res)
                resolve()
              }
            })
          })
          promiseArr.push(p)
        }
      }
      
      Promise.all(promiseArr).then((res) => {
        _url = req.actions.ym+ "customer/updateCustomer"
        params.ifVerify = this.data.ifVerify
        params.img = this.data.submitImagePath
        params.openid = this.data.userInfo.openid
        params.customerId = this.data.userInfo.id
        params.my_avatar_url = this.data.avatarUrl
        params.agree_privacy = this.data.agree_privacy ? '1' : '0',
        params.randomCode = this.data.randomCode,
        params.sessionKey = getApp().globalData.sessionId
        console.log(params)
        //return;
        utils.myResquest(params,_url,function(res){
          wx.hideLoading({success: (res) => {}})
          if(res.data.code == 401){
            wx.showModal({
              title: res.data.msg
            })
            return;
          }
          wx.showModal({
            title: '审核提示',
            content: '申请成功，请联系管理员进行审核个人信息~',
            success: function (res) {
              that.setData({ifVerify:"1"})
              if (res.confirm) {
                wx.navigateBack({delta: -1})
              } else if (res.cancel) {
                wx.navigateBack({delta: -1})
              }
            }
          })
          let userInfo = res.data.content
          console.log(res)
          console.log(userInfo)
          getApp().globalData.userInfo = userInfo;
         
        })
      })
      console.log("this.data.submitImagePath:"+JSON.stringify(this.data.submitImagePath))
      
    }else{
        let promiseArr = []
        console.log(params)
        if(this.data.avatarList.length==0 && !this.data.userInfo.my_avatar_url) {
          wx.showToast({
            title: '请上传一张个人头像',
            icon: 'none'
          })
          return false
        }
        if(this.data.userInfo.my_avatar_url != this.data.avatarList[0].url){
          let ava = new Promise((resolve, reject) => {
            utils.upload(_url,this.data.avatarList[0].url,'zjz',1,function(res){
              if(res == 'fail'){
                wx.showToast({
                  title: '发布失败，请重试',
                  icon: 'error'
                })
                reject()
              }else{
                that.data.avatarUrl = res
                resolve()
              }
            })
          })
          promiseArr.push(ava)
        }

        if(promiseArr.length > 0){
          Promise.all(promiseArr).then((res) => {
            _url = req.actions.ym+ "customer/updateCustomer"
            params.openid = this.data.userInfo.openid
            params.customerId = this.data.userInfo.id
            params.my_avatar_url = this.data.avatarUrl
            params.sessionKey = getApp().globalData.sessionId,
            params.agree_privacy = this.data.agree_privacy ? '1' : '0'
            console.log(params)
            //return;
            utils.myResquest(params,_url,function(res){
              wx.hideLoading({success: (res) => {}})
              wx.showToast({
                title: '修改信息成功！',
              })
              let userInfo = res.data.content
              console.log(res)
              console.log(userInfo)
              getApp().globalData.userInfo = userInfo;
              wx.navigateBack({
                delta: -1,
              })
            })
          })
        }else{
          params.openid = this.data.userInfo.openid
          params.customerId = this.data.userInfo.id
          params.sessionKey = getApp().globalData.sessionId
          params.agree_privacy = this.data.agree_privacy ? '1' : '0'
          console.log(params)
          //return;
          utils.myResquest(params,req.actions.ym+ "customer/updateCustomer",function(res){
            wx.hideLoading({success: (res) => {}})
            wx.showToast({
              title: '修改信息成功！',
            })
            setTimeout(function(){
              let userInfo = res.data.content
              console.log(res)
              console.log(userInfo)
              getApp().globalData.userInfo = userInfo;
              wx.navigateBack({
                delta: -1,
              })
            },1000)
            
          })
        }
        
        utils.myResquest(params,_url,function(res){
          console.log("customer/updateCustomer===>"+JSON.stringify(res))
          if(res.data.code == '200'){
            wx.hideLoading({success: (res) => {}})
            wx.showToast({
              title: '修改信息成功！',
            })
            setTimeout(function(){
              let userInfo = res.data.content
              console.log(res)
              console.log(userInfo)
              getApp().globalData.userInfo = userInfo;
              wx.navigateBack({
                delta: -1,
              })
            },1000)
          }
        })
    }
  },
  emailChange(e){
    console.log(e)
    this.setData({
      email:e.detail
    })
  },
  myNickNameChange(e){
    console.log(e)
    this.setData({myNickName:e.detail})
  },
  randomCodeChange(e){
    console.log(e)
    this.setData({
      randomCode:e.detail
    })
  },
  getRandomCode(){
    if(!this.data.email){
      wx.showToast({
        title: '请先填写邮箱！',
        icon: 'error'
      })
      return false;
    }
    let _url = req.actions.ym+ "customer/getRandomCode",params={email:this.data.email,customerId:this.data.userInfo.id},that=this
    utils.myResquest(params,_url,function(res){
      //console.log("customer/getRandomCode===>"+JSON.stringify(res))
      if(res.data.code == '200'){
        let timer = setInterval(() => {
          let countSeconds = that.data.countSeconds
          //console.log("sassa==>"+countSeconds)
          if(countSeconds < 60){
            that.setData({countSeconds:that.data.countSeconds+1,timer:timer,mailBtnStatus:true})
          }else{
            clearInterval(timer)
            that.setData({countSeconds:0,timer:null,mailBtnStatus:false})
          }
        }, 1000)
      }
    })
  },
  uploadImage:function(e){
    let that = this,_url = req.actions.ym+ "file/uploadPicture"
    
  },
  initValidate() {
    const rules = {
      myNickName: {
        required: true,
        maxlength: 20,
      },
      /*phone: {
        required: true,
        tel: true,
      },*/
      wechat: {
        maxlength: 50
      },
      qq: {
        digits: true
      },
      /*name: {
        required: true,
        maxlength: 50
      },*/
      /*email: {
        required: true,
        email: true,
      },*/
    }
    const messages = {
      myNickName: {
        required: '请填写昵称',
        maxlength: '昵称不得多于20字',
      },
      /*phone: {
        required: '请填写手机号',
        tel: '请填写有效的手机号码',
      },*/
      qq: {
        digits: '请填写有效的qq号或不填',
      },
      name: {
        required: '请填写真实姓名',
        maxlength: '名字不得过长',
      },
      /*email:{
        required: '请填写邮箱',
        email: '请填写有效的邮箱'
      }*/
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  onChangeAnonymous({ detail }) {
    this.setData({ 
      'userInfo.ifAnonymous': detail 
    })
  },
  requestNotify(){
    wx.getSetting({
      withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
      success: function(res){
        wx.requestSubscribeMessage({   // 调起消息订阅界面
          tmplIds: ['hZxrdA50XxMgLtjmROa5N2DyfCV91fMkrY0TKQIh5f0'],
          success (res) { 
            console.log('订阅消息 成功 ');
            console.log(res);
           
          },
          fail (er){
            console.log("订阅消息 失败 ");
            console.log(er);
          }
        })  
      },
      fail: function(error){
        console.log(error);
      }
    })
  },
  
})